import Vue from 'vue'
import VueRouter from "vue-router";
import Main from "../views/Main";
import PersonalCenter from "../views/PersonalCenter";
import ShoppingTrolley from "../views/ShoppingTrolley";
import Commodity from "../views/Commodity";
import Login from "../views/Login";
import MyOrder from "../views/MyOrder";
import Register from "../views/Register";
import OrderDetail from "@/components/OrderDetail";
import vuex from "../store/index"

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    redirect:'/main'
  },
  {
    name:'name',
    path: "/main",
    component:Main,
    children:[
      {
        name:'person',
        path:"/person",
        component:PersonalCenter,
        beforeEnter:function (to,form,next) {
          if (sessionStorage.getItem("userID")){
              next();
          }else {
            Vue.prototype.$dialog.confirm({
              title: '请先登录后在进行操作',
              theme: 'round-button'
            })
                .then(() => {
                  // on confirm
                  next("/login")
                })
                .catch(() => {
                  next(from.path)
                })
          }
        }
      },
      {
        name:'shopping',
        path: "/shopping",
        component: ShoppingTrolley,
        beforeEnter: function(to, from, next) {
          if (sessionStorage.getItem("userID")) {
            next();
          } else {
              Vue.prototype.$dialog.confirm({
                title: '请先登录后在进行操作',
                theme: 'round-button'
              })
                  .then(() => {
                    // on confirm
                    next("/login")
                  })
                  .catch(() => {
                    next(from.path)
                  });
          }
        }
      },
      {
        name: 'commodity',
        path: '/commodity',
        component: Commodity
      },
      {
        name: "myOrder",
        path: "/myOrder",
        component: MyOrder
      },
      {
        name:"orderDetail",
        path: "/orderDetail",
        component: OrderDetail
      }
    ]
  },
  {
    name: "login",
    path: "/login",
    component: Login
  },
  {
    name: "register",
    path: "/register",
    component: Register
  }

]

const router = new VueRouter({
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
    vuex.commit("addPreviousMenu",from.path)
    next();
})
export default router
